import './Map.scss'
import dayjs from 'dayjs'
import { useEffect, useState, useRef } from 'react'
import { useRequest, useEventEmitter, useMount } from 'ahooks'

import { Http } from '../../../../Common/Api'
import { project } from '../../../../Common/Data'
import { useLatest } from '@ant-design/pro-components'
import { CommonSmallTitle } from '../Common/SmallTitle'
import { TextList001 } from '../Common/TextList'
import { ICON } from '../../../../Common/Configure/Icon'
import { WebTemplateUrl } from '../Template/configuration'
import { initializationPlaneMap } from '../Common/PlaneMap'
import { commonImageUrl, commonUrl, Map230000 } from '../../../../Common/Configure/CommonParameter'
import { VideoUrlA01 } from '../../../../Common/Configure/Video'
import { Initialization, InitializationData } from '../../../../Common/Mars3d/Initialization'

import { MonitorA01 } from './MonitorA01'
import { SwiperTempA07 } from './SwiperTemp'
import { TemplateMapDivList } from './TemplateMap/TemplateMapDivList'

const { mars3d, turf } = window
const { hostname } = window.location
const { imageUrl } = project[hostname]
const ProjectColor = ['#1149ff']

const JSZX = ['jszx.ljkjkf.com']

const ImageType = {
    1: 'command002.png',
    2: 'command001.png',
    3: 'command002.png',
}

// 建设中心地图
export const MapA01 = ({ sceneId, MapOptions, MapSetUp, type }) => {
    const Mars3dBox = useRef()
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    const [ActiveValue, setActiveValue] = useState()
    const ActiveLater = useLatest(ActiveValue)

    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getProjectList } = useRequest(Http, {
        manual: true,
        onSuccess: ({ list }) => {
            getScenesDetailsUuid({ url: 'getScenesDetailsUuid', path: [sceneId] }).then(({ elements }) => {
                const [polyline, point] = elements
                const polylineElement = polyline.elementDetails
                const pointElement = point.elementDetails
                list.forEach(item => {
                    if (!item.customData) return
                    const add = JSON.parse(item.customData)
                    const attr = add.find(v => v.one === 'attr')?.two //0
                    const point = add.find(v => v.one === 'point')?.two //2
                    const polyline = add.find(v => v.one === 'polyline')?.two //1
                    if (!attr || !point || !polyline) return

                    item.attr = attr
                    item.center = pointElement.find(v => v.elementDetailUuid === point).center
                    polyline.split(',').forEach(key => {
                        const line = new mars3d.graphic.PolylineEntity({
                            positions: polylineElement.find(v => v.elementDetailUuid === key).position,
                            name: item.fullName + '#polyline',
                            attr,
                            id: key,
                            style: {
                                width: 10,
                                color: ProjectColor[0],
                                depthFail: false,
                                outline: true,
                                outlineColor: '#06088e',
                                outlineWidth: 3,
                            },
                        })
                        Gra.addGraphic(line)
                    })

                    const text = new mars3d.graphic.LabelEntity({
                        position: pointElement.find(v => v.elementDetailUuid === point).position,
                        name: item.fullName + '#point',
                        attr,
                        id: point,
                        show: true,
                        style: {
                            text: item.fullName,
                            font_size: 40,
                            font_family: '微软雅黑',
                            font_weight: 'bold',
                            color: '#FFFFFF',
                            outline: true,
                            outlineColor: '#06088e',
                            outlineWidth: 2,
                            visibleDepth: false,
                            scaleByDistance: true,
                        },
                    })
                    const active = new mars3d.graphic.DivGraphic({
                        position: pointElement.find(v => v.elementDetailUuid === point).position,
                        id: point + '#active',
                        name: item.fullName,
                        attr,
                        show: false,
                        style: {
                            html: `<div class="ActiveBox">
                                        <div class="title">
                                            <img src='${imageUrl}${
                                item.projectStatus === 0 ? 'HomeIcon002' : 'HomeIcon001'
                            }.png'/>
                                            <div>
                                                <div>${item.fullName}</div>
                                                <div>
                                                    <div>总投资额：${item.totalInvestAmount}亿</div>
                                                    <div>累计投资：${item.accruingAmount}亿</div>
                                                </div>
                                            </div>
                                        </div>
                                        <img src='${imageUrl}MapSelect.png' />
                                        </div>`,
                        },
                    })
                    Gra.addGraphic(text)
                    Gra.addGraphic(active)
                })

                const ClearStyle = graphic => {
                    const state = Number(list.find(v => v.attr === ActiveLater.current).remark) - 1
                    const OptionsList = Gra.getGraphicsByAttr(ActiveLater.current, 'attr')
                    const polyline = OptionsList.filter(v => v.type === 'polyline')
                    const labelData = OptionsList.filter(v => v.type === 'label')
                    const divData = OptionsList.filter(v => v.type === 'div')
                    labelData[0].show = true
                    divData[0].show = false
                    polyline.forEach(item => {
                        item.setOptions({ style: { color: ProjectColor[0], outlineColor: '#06088e' } })
                    })
                    NewStyle(graphic)
                }
                const NewStyle = graphic => {
                    const OptionsList = Gra.getGraphicsByAttr(graphic.attr, 'attr')
                    const polyline = OptionsList.filter(v => v.type === 'polyline')
                    const labelData = OptionsList.filter(v => v.type === 'label')
                    const divData = OptionsList.filter(v => v.type === 'div')
                    labelData[0].show = false
                    divData[0].show = true
                    polyline.forEach(item => {
                        item.setOptions({ style: { color: '#FFDA59', outlineColor: '#ff4901' } })
                    })
                    setActiveValue(graphic.attr)
                }
                Gra.on('click', e => {
                    const { graphic } = e
                    if (type === 'Click') {
                        if (!ActiveLater.current) NewStyle(graphic)
                        else if (ActiveLater.current && ActiveLater.current !== graphic.attr) ClearStyle(graphic)
                    }
                })
            })
        },
    })

    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            InitializationData(map, gra, res)
            setGra(gra)
            setMap(map)
        })
    })

    const { run: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, Mars3dBox, InitializationEvent),
    })

    const { runAsync: getAllPositions } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            if (Map.getLayerById('Helmet')) Map.getLayerById('Helmet').clear()
            else Map.addLayer(new mars3d.layer.GraphicLayer({ id: 'Helmet' }))
            Object.keys(res).forEach(key => {
                if (res[key]?.lon && res[key]?.lat) {
                    const { lon, lat, helmetType } = res[key]
                    const active = new mars3d.graphic.DivGraphic({
                        position: [lon, lat, 0],
                        style: {
                            clampToGround: true,
                            html: `<div class="HelmetPosition">
                                    <div>${key}</div>
                                    <img src='${commonImageUrl}${ImageType[helmetType]}' />
                                </div>
                                `,
                        },
                    })
                    Map.getLayerById('Helmet').addGraphic(active)
                }
            })
        },
    })

    useEffect(() => {
        if (JSZX.includes(hostname)) {
            const { map, gra } = initializationPlaneMap(Mars3dBox, MapOptions, MapSetUp)
            setMap(map)
            setGra(gra)
        } else {
            getScenes({ url: `getScenesID`, path: [sceneId] })
        }
    }, [MapOptions, MapSetUp, getScenes, sceneId])

    useEffect(() => {
        if (Map && Gra) {
            getProjectList({ url: 'getProjectList' })
            if (type === 'Helmet') getAllPositions({ url: 'getHelmetAllPositions' })
        }
    }, [Gra, Map, getAllPositions, getProjectList, type])

    return (
        <>
            <div className="MapA01" ref={Mars3dBox} />
            {!JSZX.includes(hostname) && <img className="Mask" src={WebTemplateUrl + 'Mask.png'} alt="" />}
        </>
    )
}

const VideoMapping = {
    'cce47231-19da-4c9e-99a4-5507588d4ba8': 'a1d13b84-1170-46ab-907e-067c8b0fce09',
    '36ac1ee5-5880-4eb5-bd48-74b98049b0ab': '83dd1899-c021-4965-81a5-4ef200625c68',
    1: 'f65f2bdf-3301-460b-9c83-64544438b039',
}

export const MapA02 = ({ sceneId, type }) => {
    const Mars3dBox = useRef()
    const [Map, setMap] = useState()

    const [FilesList, setFilesList] = useState()
    const [Active, setActive] = useState()
    const [center, setCenter] = useState()
    const [Json, setJson] = useState()
    const [DbIdData, setDbIdData] = useState()

    const [VideoUuid, setVideoUuid] = useState(VideoMapping['cce47231-19da-4c9e-99a4-5507588d4ba8'])

    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getJson } = useRequest(Http, { manual: true, onSuccess: res => setJson(res || {}) })
    const { runAsync: getItemDetal } = useRequest(Http, { manual: true })

    const { runAsync: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setCenter(JSON.parse(res.center))
            Initialization(res, Mars3dBox, InitializationEvent)
        },
    })
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        setMap(map)
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            const { elements, files } = res
            InitializationData(map, gra, { elements })
            const filesData = [...files, { scenesDetailsUuid: '2', tableName: '滨北铁路公铁分离式桥' }]
            setFilesList(filesData)
            onSelect(files[0].scenesDetailsUuid, filesData, map)
            map.on('click', ({ graphic, layer }) => {
                if (layer && layer.type === '3dtiles') {
                    setDbIdData()
                    const { url } = layer.options
                    const { DbId } = graphic.attr
                    let arr = url.split('/')
                    arr[arr.length - 1] = `info/${parseInt(DbId / 100)}.json`
                    const jsonUrl = arr.slice(-3).join('/')
                    getItemDetal({ url: 'getPicJsonInfoByUuid', data: { uuid: jsonUrl } }).then(res =>
                        setDbIdData(res.data[DbId]),
                    )
                } else setDbIdData()
            })
        })
    })

    useMount(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
        getJson({ url: 'getJsonInfoByUuid', data: { uuid: 'OverallProgress' } })
    })

    const mapping = {
        'cce47231-19da-4c9e-99a4-5507588d4ba8': {
            deckDbId: [3958, 3973],
            markDbId: [50622, 50625],
            guarDbid: [],
        },
        '36ac1ee5-5880-4eb5-bd48-74b98049b0ab': {
            deckDbId: [2290, 2319, 2338, 2299, 2309, 2329],
            markDbId: [2529, 2526],
            guarDbid: [2284, 2287, 2313, 2316, 2320, 2332, 2335, 2339, 2293, 2296, 2300, 2303, 2306, 2310, 2323, 2326],
        },
    }

    const onSelect = (uuid, files, map) => {
        if (uuid.length === 1) return
        const ModalList = files || FilesList
        const { constitutesUuid } = ModalList.find(v => v.scenesDetailsUuid === uuid)
        const selectData = Json?.hasOwnProperty(constitutesUuid) ? Json[constitutesUuid] : []
        const mapData = map || Map
        const { tableName, center, storagePath, isEnabled, longitude, latitude, altitude, rotate, scale } =
            ModalList.find(v => v.scenesDetailsUuid === uuid)
        setActive(uuid)
        setVideoUuid(VideoMapping[uuid])
        mapData.centerAt(center)
        const currentModal = mapData.getLayerById(uuid)
        if (!currentModal) {
            // eslint-disable-next-line no-template-curly-in-string
            const entranceDbId = selectData.map(item => ['${DbId}===' + item, 'rgba(0, 255, 0, 1)'])
            // eslint-disable-next-line no-template-curly-in-string
            const deckDbId = mapping[uuid].deckDbId.map(item => ['${DbId}===' + item, 'rgba(38,38,38,1)'])
            // eslint-disable-next-line no-template-curly-in-string
            const markDbId = mapping[uuid].markDbId.map(item => ['${DbId}===' + item, 'rgba(251,251,251,1)'])
            // eslint-disable-next-line no-template-curly-in-string
            const guarDbid = mapping[uuid].guarDbid.map(item => ['${DbId}===' + item, 'rgba(223,134,13,1)'])

            const TilesetLayer = new mars3d.layer.TilesetLayer({
                id: uuid,
                name: tableName,
                url: storagePath,
                maximumScreenSpaceError: 1,
                maximumMemoryUsage: 1024,
                skipLevelOfDetail: true,
                preferLeaves: true,
                dynamicScreenSpaceError: true,
                cullWithChildrenBounds: false,
                scale: scale || 1,
                show: Number(isEnabled),
                position: { lng: Number(longitude), lat: Number(latitude), alt: Number(altitude) },
                rotation: rotate,
                highlight: { type: mars3d.EventType.click, color: 'rgba(0, 255, 255, 1)' },
                style: {
                    color: {
                        conditions: [
                            ...entranceDbId,
                            ...deckDbId,
                            ...markDbId,
                            ...guarDbid,
                            ['true', 'rgba(188,188,188,1)'],
                        ],
                    },
                },
            })
            mapData.addLayer(TilesetLayer)
        }
    }

    useEffect(() => {
        return () => {
            if (Map) {
                Map.destroy()
            }
        }
    }, [Map])

    return (
        <div className="MapA02">
            <img className="Mask" src={WebTemplateUrl + 'Mask.png'} alt="" />
            <div className="Map" ref={Mars3dBox} />
            <div className="FilesList">
                {FilesList &&
                    FilesList.map(({ scenesDetailsUuid, tableName }) => (
                        <div
                            key={scenesDetailsUuid}
                            onClick={() => onSelect(scenesDetailsUuid)}
                            className={Active === scenesDetailsUuid ? 'active' : ''}
                        >
                            {tableName}
                        </div>
                    ))}
                <div className="AllObj" onClick={() => Map.centerAt(center)}>
                    项目全览
                </div>
            </div>

            {type === 'video' && (
                <div className="VideoList">
                    <CommonSmallTitle title="桥梁施工工艺动画">
                        <SwiperTempA07 importantPartUuid={VideoUuid} />
                    </CommonSmallTitle>
                </div>
            )}

            {DbIdData && (
                <div className="DbIdData">
                    <CommonSmallTitle title={`${DbIdData.name} - 构建详情`}>
                        {DbIdData.categories.map(({ name, props }, index) => {
                            if (!name.includes('__')) {
                                const { names, values } = props
                                return (
                                    <div className="DbIdData_box" key={index}>
                                        <div className="DbIdData_name">{name}</div>
                                        <div className="DbIdData_data">
                                            <div className="DbIdData_label">
                                                {names.map((item, index) => (
                                                    <div key={index}>{item}</div>
                                                ))}
                                            </div>
                                            <div className="DbIdData_value">
                                                {values.map((item, index) => (
                                                    <div key={index}>{item}</div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                )
                            } else {
                                return false
                            }
                        })}
                    </CommonSmallTitle>
                </div>
            )}
        </div>
    )
}

export const MapA03 = ({ sceneId }) => {
    const Mars3dBox = useRef()
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    const [RiskList, setRiskList] = useState([])

    const { runAsync: getRiskSourceList } = useRequest(Http, { manual: true })
    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, Mars3dBox, InitializationEvent),
    })
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        setMap(map)
        setGra(gra)
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            InitializationData(map, gra, { elements: res.elements })
            getRiskSourceList({
                url: 'getGetSecurityGetRiskSourceList',
                data: { eventDate: dayjs().format('YYYY-MM') },
            }).then(res => {
                res.list.forEach(({ uuid, tableName, lng, lat, organizationName, mileage, grade }) => {
                    const src =
                        grade === '重大风险'
                            ? 'https://image.ljkjkf.com/intellisiteSystem_TieKe/Common/mars3d/riskA01.png'
                            : 'https://image.ljkjkf.com/intellisiteSystem_TieKe/Common/mars3d/riskA02.png'

                    const graphic = new mars3d.graphic.DivGraphic({
                        id: uuid,
                        position: [lng, lat, 0],
                        style: {
                            html: `
                            <div class="MapA03DIV">
                                <img src="${src}"/>
                                <div>
                                    <div>${tableName}</div>
                                    <div>${organizationName}标段 ${mileage}</div>
                                </div>
                            </div>`,
                            clampToGround: true,
                        },
                    })
                    gra.addGraphic(graphic)
                })
                setRiskList(res.list)
            })
        })
    })

    useMount(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    })

    const Top = [
        { uuid: 1, label: '风险源名称', value: 'tableName', flex: 2 },
        { uuid: 2, label: '风险等级', value: 'grade', flex: 1 },
        { uuid: 3, label: '位置（桩号）', value: 'mileage', flex: 2 },
    ]

    const ClickEvent = useEventEmitter()
    ClickEvent.useSubscription(val => {
        console.log('[点击回调]', Gra.getGraphicById(val.uuid))

        Map.flyToGraphic(Gra.getGraphicById(val.uuid))
    })

    return (
        <div className="MapA03">
            <img className="Mask" src={WebTemplateUrl + 'Mask.png'} alt="" />
            <div className="Map" ref={Mars3dBox} />
            <CommonSmallTitle title="风险点列表">
                <div className="MapList">
                    <div>
                        {ICON['jinggao']}
                        <div>本月风险要点 : </div>
                        <div>{RiskList.length}</div>
                    </div>
                    <TextList001 Top={Top} data={RiskList} click={ClickEvent} />
                </div>
            </CommonSmallTitle>
        </div>
    )
}

export const MapA04 = () => {
    const List = [
        { uuid: 1, title: '运输船管控' },
        { uuid: 2, title: '车辆运输管控' },
        { uuid: 3, title: '动画展示' },
        { uuid: 4, title: '高点监控' },
    ]
    const [Active, setActive] = useState(1)

    const TopA01 = [
        { uuid: 1, label: '名称', value: 'A01', flex: 2 },
        { uuid: 2, label: '日期', value: 'A02', flex: 1 },
    ]
    const TopA02 = [
        { uuid: 1, label: '港口', value: 'A01', flex: 1 },
        { uuid: 2, label: '泊位', value: 'A02', flex: 1 },
        { uuid: 3, label: '停靠次数', value: 'A03', flex: 1 },
    ]

    const DataA01 = [
        { uuid: 1, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 2, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 3, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 4, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 5, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 6, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 7, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 8, A01: '有外来船只驶入航道', A02: '2023-10-13' },
        { uuid: 9, A01: '有外来船只驶入航道', A02: '2023-10-13' },
    ]

    const DataA02 = [
        { uuid: 1, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-1', A03: Math.floor(Math.random() * 100) },
        { uuid: 2, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-2', A03: Math.floor(Math.random() * 100) },
        { uuid: 3, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-3', A03: Math.floor(Math.random() * 100) },
        { uuid: 4, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-4', A03: Math.floor(Math.random() * 100) },
        { uuid: 5, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-5', A03: Math.floor(Math.random() * 100) },
        { uuid: 6, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-6', A03: Math.floor(Math.random() * 100) },
        { uuid: 7, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-7', A03: Math.floor(Math.random() * 100) },
        { uuid: 8, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-8', A03: Math.floor(Math.random() * 100) },
        { uuid: 9, A01: Math.random() <= 0.5 ? '南岸' : '北岸', A02: 'N1-9', A03: Math.floor(Math.random() * 100) },
    ]

    const DataA03 = [
        { uuid: 1, icon: 'qiaoliang1', title: '钢便桥当前总数', value: Math.floor(Math.random() * 100) },
        { uuid: 2, icon: 'gaojing_daolujishui', title: '南岸车辆数量', value: Math.floor(Math.random() * 100) },
        { uuid: 3, icon: 'gaojing_daolujishui', title: '北岸车辆数量', value: Math.floor(Math.random() * 100) },
        {
            uuid: 4,
            icon: 'liangbiaoguanli_huaban1',
            title: '车辆平均速度',
            value: `${Math.floor(Math.random() * 100)}`,
        },
    ]

    // getVideos: `${API}/home/videos`,

    const [Video, setVideo] = useState()

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setVideo(res.list[0])
        },
    })

    useMount(() => {
        runAsync({ url: 'getVideos', data: { importantPartUuid: 'e7b380ed-0c4e-48a4-8e1a-b62990c0985b' } })
    })

    return (
        <div className="MapA04">
            <div className="Nav">
                <div className="NavBox">
                    {List.map(({ uuid, title }) => (
                        <div key={uuid} className={Active === uuid ? 'active' : ''} onClick={() => setActive(uuid)}>
                            {title}
                        </div>
                    ))}
                </div>
            </div>
            <div className="Box">
                {Active === 1 && (
                    <div>
                        {/* <img src={imageUrl + 'B471.jpg'} alt="" />
                        <div className="Left">
                            <CommonSmallTitle title="高点监控预警" style={{ marginBottom: 16 }}>
                                <div className="B471Box">
                                    <div className="MapList">
                                        <div>
                                            {ICON['jinggao']}
                                            <div>今日预警 : </div>
                                            <div>{Math.floor(Math.random() * 10) + 1}</div>
                                        </div>
                                    </div>
                                    <TextList001 Top={TopA01} data={DataA01} />
                                </div>
                            </CommonSmallTitle>
                            <CommonSmallTitle title="今日泊位统计">
                                <div className="Item">
                                    <TextList001 Top={TopA02} data={DataA02} />
                                </div>
                            </CommonSmallTitle>
                        </div>
                        <div className="Right">
                            <CommonSmallTitle title="本周泊位统计" style={{ marginBottom: 16 }}>
                                <div className="Item">
                                    <TextList001 Top={TopA02} data={DataA02} />
                                </div>
                            </CommonSmallTitle>
                            <CommonSmallTitle title="本月泊位统计">
                                <div className="Item">
                                    <TextList001 Top={TopA02} data={DataA02} />
                                </div>
                            </CommonSmallTitle>
                        </div> */}
                    </div>
                )}
                {Active === 2 && (
                    <div>
                        <img src={imageUrl + 'B472.jpg'} alt="" />
                        <div className="Left">
                            <CommonSmallTitle title="车辆统计">
                                <div className="B472Box">
                                    {DataA03.map(({ uuid, icon, title, value }) => (
                                        <div key={uuid}>
                                            {ICON[icon]}
                                            <div>{title}</div>
                                            <div>{value}</div>
                                        </div>
                                    ))}
                                </div>
                            </CommonSmallTitle>
                        </div>
                    </div>
                )}

                {Active === 3 && (
                    <div className="vidoe">
                        <CommonSmallTitle title="动画展示">
                            {Video && <VideoUrlA01 fileUrl={Video.videoAttachment.fileUrl} />}
                        </CommonSmallTitle>
                    </div>
                )}
                {Active === 4 && (
                    <div className="vidoe">
                        <CommonSmallTitle title="高点监控">
                            <MonitorA01 index={1} size={1} />
                        </CommonSmallTitle>
                    </div>
                )}
            </div>
        </div>
    )
}

const KongMap = {
    scene: {
        sceneMode: 1,
        center: { lat: 35.535081, lng: 128.546309, alt: 2333542, heading: 356.7, pitch: -69.7 },
        orderIndependentTranslucency: false,
        contextOptions: { webgl: { alpha: true } },
        showSun: false,
        showMoon: false,
        showSkyBox: false,
        showSkyAtmosphere: false,
    },
    control: {
        homeButton: true,
        zoom: true,
        fullscreenButton: true,
        geocoder: 'gaode',
        baseLayerPicker: false,
        locationBar: true,
        distanceLegend: { enabled: false },
        compass: false,
    },
    basemaps: [
        {
            id: 1,
            type: 'tdt',
            layer: 'img_d',
            name: '天地图影像(无标注)',
            key: ['66157ab348d37d969fdc61d1a6f45c6e'],
            popup: 'all',
            show: true,
        },
    ],
    layers: [],
    terrain: { url: '//data.mars3d.cn/terrain', show: true },
    templateValues: {
        dataServer: 'http://data.mars3d.cn',
        gltfServerUrl: 'http://data.mars3d.cn/gltf',
    },
}

// 工建首页地图
export const MapA05 = ({ MapEvent, MapClickEvent }) => {
    const MapBox = useRef()
    MapEvent.useSubscription(val => renderCity(val))

    const [Gra, setGra] = useState()

    const renderCity = data => {
        if (Gra) {
            data.list.forEach(item => {
                const div = new mars3d.graphic.DivGraphic(TemplateMapDivList['TemplateMapDiv006']({ item }))
                Gra.addGraphic(div)
                div.on('click', ({ graphic }) => {
                    const { uuid } = data.list.find(v => v.code === graphic.id)
                    MapClickEvent.emit(uuid)
                })
            })
        } else setTimeout(() => renderCity(data), 500)
    }

    const initMapA05 = () => {
        KongMap.scene.center = { lat: 42.118364, lng: 128.63971, alt: 1949386.7, heading: 356.7, pitch: -69.7 }
        const map = new mars3d.Map(MapBox.current, KongMap)
        const gra = new mars3d.layer.GraphicLayer()
        const clip = new mars3d.thing.TerrainClip({ clipOutSide: true, czm: false })
        // const bloom = new mars3d.effect.BloomEffect()
        setGra(gra)
        // map.addEffect(bloom)
        map.addLayer(gra)
        map.addThing(clip)
        mars3d.Util.fetchJson({ url: commonUrl + 'Scene/json/230000_full.json' }).then(res => {
            mars3d.Util.geoJsonToGraphics(res).forEach(({ attr, positions }) => {
                // 纹理
                clip.addArea(positions)
                // 边界线
                const polyline = new mars3d.graphic.PolylineEntity({
                    attr: 'BoundaryLine',
                    positions,
                    style: {
                        width: 4,
                        opacity: 1,
                        clampToGround: true,
                        materialType: 'LineFlowColor',
                        materialOptions: {
                            color: 'rgba(255, 190, 98, 0.85)',
                            speed: 2,
                            alpha: 0.35,
                            percent: 0.1,
                        },
                    },
                })
                gra.addGraphic(polyline)
                // 边界墙
                const Wall = new mars3d.graphic.WallPrimitive({
                    attr: 'BoundaryWall',
                    positions,
                    style: {
                        setHeight: -60000,
                        diffHeight: 60000,
                        closure: false,
                        materialType: 'LineFlow',
                        materialOptions: {
                            image: 'http://mars3d.cn/img/textures/fence.png',
                            color: 'rgba(1, 95, 121, 0.85)',
                            // mixt: true,
                            speed: 5,
                            axisY: true,
                        },
                    },
                })
                gra.addGraphic(Wall)
                // 面层
                const graphic = new mars3d.graphic.PolygonPrimitive({
                    positions,
                    attr: 'Coverage',
                    style: {
                        diffHeight: 0,
                        clampToGround: true,
                        materialType: 'Color',
                        materialOptions: {
                            color: 'rgba(35, 102, 149, 0.15)',
                        },
                    },
                })
                gra.addGraphic(graphic)
            })
        })

        Object.values(Map230000).forEach(({ name, position }) => {
            // console.log('[name]', name)
            // console.log('[position]', position)
            // const div = new mars3d.graphic.DivGraphic(TemplateMapDivList['TemplateMapDiv006']({ item }))
            // gra.addGraphic(div)
        })
    }

    useEffect(() => {
        if (MapBox) initMapA05()
    }, [MapBox])

    return (
        <div className="MapA05">
            <div className="Map" ref={MapBox} />
        </div>
    )
}

// 洋浦首页
export const MapA06 = ({ sceneId, type, center }) => {
    const MapBox = useRef()

    const [Gra, setGra] = useState()
    const [Map, setMap] = useState()
    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })

    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            if (center) map.centerAt(center)
            setGra(gra)
            setMap(map)
            if (type === 1) {
                getColor({ url: 'getJsonInfoByUuid', data: { uuid: 'YPColor' } }).then(yp => {
                    console.log(yp)
                    let divItem = []
                    const divList = {
                        elementDetails: [],
                        elementType: 'div',
                        isEnabled: 1,
                        sortId: 1100,
                        storageType: 0,
                        styleName: 'DIV007',
                        tableName: '占地图标',
                    }
                    let elements = res.elements[0].elementDetails
                    yp.forEach(({ start, end, color, text, direction }) => {
                        elements.forEach((item, index) => {
                            if (index + 1 >= start && index + 1 <= end) item.color = color
                        })
                        const [position] = elements.find(
                            v => v.sortId === start + Math.floor((end - start) / 2),
                        ).position
                        divItem = [
                            ...divItem,
                            { tableName: `${direction},${text}`, sortId: 1, isEnabled: 1, color, position },
                        ]
                    })
                    res.elements[0].elementDetails = elements
                    divList.elementDetails = divItem
                    res.elements.push(divList)
                    InitializationData(map, gra, res)
                    renderDom(map, gra)
                })
            } else {
                InitializationData(map, gra, res)
                renderDom(map, gra)
            }
        })
    })

    const renderDom = (map, gra) => {
        mars3d.Util.fetchJson({ url: commonUrl + 'Scene/json/460400.json' }).then(res => {
            mars3d.Util.geoJsonToGraphics(res).forEach(({ attr, positions }) => {
                // 纹理
                map.thing.terrainClip.addArea(positions)
                map.thing.terrainClip.clipOutSide = true
                map.thing.terrainClip.czm = false
                // 边界线
                const polyline = new mars3d.graphic.PolylineEntity({
                    attr: 'BoundaryLine',
                    positions,
                    style: {
                        width: 4,
                        opacity: 1,
                        clampToGround: true,
                        materialType: 'LineFlowColor',
                        materialOptions: {
                            color: 'rgba(255, 190, 98, 0.85)',
                            speed: 2,
                            alpha: 0.35,
                            percent: 0.1,
                        },
                    },
                })
                gra.addGraphic(polyline)
                // 边界墙
                const Wall = new mars3d.graphic.WallPrimitive({
                    attr: 'BoundaryWall',
                    positions,
                    style: {
                        setHeight: -15000,
                        diffHeight: 15000,
                        closure: false,
                        materialType: 'LineFlow',
                        materialOptions: {
                            image: 'http://mars3d.cn/img/textures/fence.png',
                            color: 'rgba(1, 95, 121, 0.85)',
                            speed: 5,
                            axisY: true,
                        },
                    },
                })
                gra.addGraphic(Wall)
                // 面层
                const graphic = new mars3d.graphic.PolygonPrimitive({
                    positions,
                    attr: 'Coverage',
                    style: {
                        diffHeight: 0,
                        clampToGround: true,
                        materialType: 'Color',
                        materialOptions: {
                            color: 'rgba(35, 102, 149, 0.15)',
                        },
                    },
                })
                gra.addGraphic(graphic)
            })
        })
    }

    const { runAsync: getColor } = useRequest(Http, { manual: true })
    const { runAsync: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const additional = {
                scene: {
                    sceneMode: 3,
                    orderIndependentTranslucency: false,
                    contextOptions: { webgl: { alpha: true } },
                    showSun: false,
                    showMoon: false,
                    showSkyBox: false,
                    showSkyAtmosphere: false,
                    requestRenderMode: true,
                    scene3DOnly: true,
                    shadows: false,
                    removeDblClick: true,
                    fog: true,
                    fxaa: true,
                },
            }
            Initialization(res, MapBox, InitializationEvent, additional)
        },
    })

    useEffect(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    }, [getScenes, sceneId])

    return (
        <div className="MapA05">
            <div className="Map" ref={MapBox} />
        </div>
    )
}

export const MapA07 = ({ sceneId }) => {
    const MapBox = useRef()

    const [Gra, setGra] = useState()
    const [Map, setMap] = useState()
    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getColor } = useRequest(Http, { manual: true })

    const InitializationEvent = useEventEmitter()
    const { runAsync: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, MapBox, InitializationEvent),
    })

    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            setGra(gra)
            setMap(map)
            InitializationData(map, gra, res)
            getColor({ url: 'getJsonInfoByUuid', data: { uuid: 'YPColorA02' } }).then(yp => {
                const mainLay = gra.getGraphicById('22d3a01a-536f-4db4-9fa2-a0bb93723e1c').toGeoJSON()
                yp.forEach(({ uuid, positions, text, color, direction }) => {
                    const markLay = new mars3d.graphic.PolygonEntity({ positions: JSON.parse(positions) }).toGeoJSON()
                    const geojson = turf.intersect(mainLay, markLay)
                    const point = turf.centroid(geojson)
                    const cross = mars3d.Util.geoJsonToGraphics(geojson)[0]
                    cross.type = 'polygon'
                    cross.style = { color, clampToGround: true }
                    gra.addGraphic(cross)
                    gra.addGraphic(
                        new mars3d.graphic.DivGraphic({
                            id: uuid,
                            position: point.geometry.coordinates,
                            hasZIndex: true,
                            style: {
                                className: 'DIV007',
                                clampToGround: true,
                                html: ` 
                                    <div class="Mars3DDiv007 ${direction}" style='--color:${color}'>
                                        <div class='title'>${text}</div>
                                        <div class='triangle' />
                                    </div>`,
                            },
                        }),
                    )
                })
            })
        })
    })

    useEffect(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    }, [getScenes, sceneId])

    const [Positions, setPositions] = useState()

    const onClick = () => {
        const positions = typeof Positions === 'string' ? JSON.parse(Positions) : Positions
        const layer1 = Gra.getGraphicById('22d3a01a-536f-4db4-9fa2-a0bb93723e1c').toGeoJSON()
        const layer2 = new mars3d.graphic.PolygonEntity({ positions }).toGeoJSON()
        const geojson = turf.intersect(layer1, layer2)
        const dian = turf.centroid(geojson)

        Gra.addGraphic(
            new mars3d.graphic.PointEntity({
                position: dian.geometry.coordinates,
                style: { color: '#ff0000', clampToGround: true, visibleDepth: false },
            }),
        )

        const intersectGraphic = mars3d.Util.geoJsonToGraphics(geojson)[0]
        intersectGraphic.type = 'polygon'
        intersectGraphic.style = { color: '#0ff', clampToGround: true }
        Gra.addGraphic(intersectGraphic)
    }

    return (
        <div className="MapA05">
            <div className="Map" ref={MapBox} />
        </div>
    )
}

export const BeiHuanAdaqiao = ({ sceneId }) => {
    const MapBox = useRef()
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            InitializationData(map, gra, res)
        })
    })

    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, MapBox, InitializationEvent),
    })

    useEffect(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    }, [getScenes, sceneId])

    return <div className="BeiHuanAdaqiao" ref={MapBox} />
}
